<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    :before-close="closeGoodsDialog"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="单品编码" prop="code">
        <el-input
          placeholder=""
          v-model="dataForm.code"
          maxlength="20"
        ></el-input>
      </el-form-item>
      <el-form-item label="单品名称" prop="title">
        <el-input
          placeholder=""
          v-model="dataForm.title"
          maxlength="50"
        ></el-input>
      </el-form-item>
      <el-form-item label="单品分组" prop="goods_group_id">
        <!-- <el-tag v-if="groupName != ''">{{groupName}}</el-tag>
       <div  class="flexcenter">
       	<el-button @click="goodsGroup()">选择商品店铺分组</el-button>
       	<span class="textWorning">请选择二级分组</span>
       </div> -->
        <!-- <el-cascader v-model="dataForm.goods_group_id" :options="productGroupingTableData" :show-all-levels="false" @change="getTemplateRow"></el-cascader> -->
        <el-select
          v-model="dataForm.goods_group_id"
          placeholder="请选择"
          @change="getTemplateRow"
        >
          <el-option
            v-for="item in productGroupingTableData"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <!--选择商品分组-->
      <!-- <el-dialog title="商品分组" :append-to-body="true" :visible.sync="dialogProductGrouping" width="30%">
	  	<el-table ref="multipleTable" :data="productGroupingTableData" tooltip-effect="dark" border style="width: 100%"
	  	 row-key="id" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
	  		<el-table-column  type="selection" width="55" align=center>
            <template slot-scope="scope">
               <el-radio :label="scope.$index" v-model="dataForm.goods_group_id"  :disabled='scope.row.isDisabled'
                  @change.native="getTemplateRow(scope.$index,scope.row)" style="margin-left: 10px;">&nbsp;</el-radio>
               </template>
         </el-table-column>
	  		<el-table-column prop="name" label="分类名称" align=center>
	  		</el-table-column>

	  	</el-table>
	 	<span slot="footer" class="dialog-footer">
	  		<el-button @click="dialogProductGrouping = false">取 消</el-button>
	  		<el-button type="primary" @click="dialogProduct">确 定</el-button>
	  	</span>
	  </el-dialog>
 -->
      <el-form-item label="单品图片" prop="cover_temp">
        <div v-show="false">{{ dataForm.cover_temp }}</div>
        <Imglist
          @updataImg="updataImg"
          :limit="1"
          :value="dataForm.cover_image"
          :dialogVisible="visible"
        ></Imglist>
      </el-form-item>
      <el-form-item label="单品规格" prop="sku">
        <el-input
          placeholder=""
          v-model="dataForm.sku"
          maxlength="50"
        ></el-input>
      </el-form-item>
      <el-form-item label="单品单位" prop="unit">
        <el-input
          placeholder=""
          v-model="dataForm.unit"
          maxlength="10"
        ></el-input>
      </el-form-item>
      <el-form-item label="初始库存" prop="able_stock">
        <!--  @input="limitInputs($event,'able_stock')" -->
        <el-input-number
          :min="1"
          :max="999999"
          v-model="dataForm.able_stock"
          :disabled="dataForm.id ? true : false"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="单品成本" prop="cost_price">
        <el-input
          placeholder=""
          v-model="dataForm.cost_price"
          maxlength="8"
          @input="limitInput($event, 'cost_price')"
        ></el-input>
      </el-form-item>
      <el-form-item label="上下架" prop="added" v-if="!isUp">
        <el-radio-group v-model="dataForm.added">
          <el-radio :label="false">下架</el-radio>
          <el-radio :label="true">上架</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">提交</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { treeDataTranslate } from '@/utils'
import Imglist from './../../oss/oss-uploadImg'
import seviceApi from '@/api/serviceApi.js'
export default {
  components: {
    Imglist
  },
  data() {
    return {
      visible: false,
      dialogImageUrl: '',
      dialogVisible: false,
      // isDisabled:false,
      dialogProductGrouping: false,
      productGroupingTableData: [], // 商品分组table数据
      groupingMultipleSelection: [], // 选中商品分组
      groupName: '',
      dataForm: {
        id: '',
        code: '',
        title: '',
        goods_group_id: '',
        cover_image: [],
        cover_temp: [],
        sku: '',
        unit: '',
        able_stock: 0,
        cost_price: null,
        order_index: 0,
        added: null
      },
      cover_image: [],
      options: [], // 单品分组
      dataRule: {
        code: [
          {
            required: true,
            message: '单品编码不能为空',
            trigger: 'blur'
          }
        ],
        title: [
          {
            required: true,
            message: '单品名称不能为空',
            trigger: 'blur'
          }
        ],
        goods_group_id: [
          {
            required: true,
            message: '请选择单品分组',
            trigger: 'blur'
          }
        ],
        cover_temp: [
          {
            required: true,
            message: '单品图片不能为空',
            trigger: 'change'
          }
        ],
        sku: [
          {
            required: true,
            message: '单品规格不能为空',
            trigger: 'blur'
          }
        ],
        unit: [
          {
            required: true,
            message: '单品单位不能为空',
            trigger: 'blur'
          }
        ],
        able_stock: [
          {
            required: true,
            message: '单品初始库存不能为空',
            trigger: 'blur'
          }
        ],
        cost_price: [
          {
            required: true,
            message: '单品成本不能为空',
            trigger: 'blur'
          }
        ],
        added: [
          {
            required: true,
            message: '请选择上下架',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  props: {
    //是否默认是上架
    isUp: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    init(id) {
      this.dataForm.id = id || 0
      this.visible = true
      this.dataForm.cover_image = []
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
      })
      if (this.dataForm.id != 0) {
        seviceApi.getSinglegoodsInfo(id).then(res => {
          if (res && res.data.code == 200) {
            this.dataForm = res.data.data
            if (res.data.data.cover_image) {
              this.dataForm.cover_temp = res.data.data.cover_image
              this.dataForm.cover_image = res.data.data.cover_image.split(',')
            }
            console.log(this.dataForm.cover_image instanceof Array)
          }
          console.log(res.data.data.cover_image)
        })
      }
      // 获取单品分组
      seviceApi.getGoodsGroupsList().then(res => {
        // if (res && res.data.code == 200) {
        //   var arry = []
        //   for (var i = 0; i < res.data.list.length; i++) {
        //     arry = arry.concat(res.data.list[i].children)
        //   }
        //   this.options = arry
        // }
        if (res && res.data.code == 200) {
          for (var i = 0; i < res.data.list.length; i++) {
            if (res.data.list[i].parent_id == 0) {
              res.data.list[i].value = res.data.list[i].id
              res.data.list[i].label = res.data.list[i].name
            }
            for (var k = 0; k < res.data.list[i].children.length; k++) {
              if (res.data.list[i].children[k].parent_id > 0) {
                res.data.list[i].children[k].value =
                  res.data.list[i].children[k].id
                res.data.list[i].children[k].label =
                  res.data.list[i].children[k].name
                delete res.data.list[i].children[k].children
              }
            }
          }
          this.productGroupingTableData = res.data.list
        }
      })
    },
    closeGoodsDialog () {
      this.$emit('closeGoodsDialog')
      console.log()
    },
    // 商品分组
    // 选中
    getTemplateRow (value) {
      this.dataForm.goods_group_id = value
    },
    // 上传图片
    updataImg (e) {
      this.cover_image = e
      this.dataForm.cover_temp = e
    },
    limitInput(value, name) {
      this.dataForm[name] =
        ('' + value) // 第一步：转成字符串
          .replace(/[^\d^\.]+/g, '') // 第二步：把不是数字，不是小数点的过滤掉
          .replace(/^0+(\d)/, '$1') // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
          .replace(/^\./, '0.') // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
          .match(/^\d*(\.?\d{0,2})/g)[0] || '' // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，而且小数点后面只能有0到2位小数
    },
    limitInputs(value, name) {
      if (!/^\d+$/.test(value)) {
        this.dataForm[name] = /^\d+/.exec(value)
      }
      return false
    },
    // 提交
    dataFormSubmit() {
      let form = JSON.parse(JSON.stringify(this.dataForm))
      if (this.cover_image.length > 0) {
        form.cover_image = this.cover_image.join(',')
      }
      if (typeof form.cover_image === 'string') {
        form.cover_image = form.cover_image
        // console.log('字符串')
      } else {
        form.cover_image = form.cover_image.join(',')
        // console.log('数组')
      }
      if (this.isUp) form.added = true
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.dataForm.id == 0) {
            seviceApi.saveSinglegoods(form).then(res => {
              if (res && res.data.code == 200) {
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
                this.cover_image = []
                this.dataForm.cover_image = []
                this.visible = false
                this.$emit('updataList', res.data.data)
              }
            })
          } else {
            seviceApi.updateSinglegoods(form).then(res => {
              if (res && res.data.code == 200) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.cover_image = []
                this.dataForm.cover_image = []
                this.visible = false
                this.$emit('updataList', res.data.data)
              }
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-scrollbar__wrap {
  margin-right: 0px !important;
}
</style>
